package router

import (
	"gitee.com/igolang/imoney/internal/common/constants"
	"gitee.com/igolang/imoney/internal/core/logger"
	"gitee.com/igolang/imoney/internal/router/middleware"
	"gitee.com/igolang/pkg/xcfg"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type initRoute func(in *gin.Engine)

var initRoutes = []initRoute{middlewares, root, debug}

func Add(route initRoute) {
	initRoutes = append(initRoutes, route)
}

func Init(in *gin.Engine) {
	for _, v := range initRoutes {
		v(in)
	}
}

func root(engine *gin.Engine) {
	engine.GET("/", pong)
	engine.GET("ping", pong)
}

func pong(ctx *gin.Context) {
	ctx.String(http.StatusOK, "PONG")
}

func middlewares(engine *gin.Engine) {
	engine.Use(
		func(ctx *gin.Context) {
			ctx.Set(constants.RouterMiddleRequestTimeKey, time.Now())
		},
		middleware.Limited(xcfg.GetInt("server.maxConcurrency")),
		middleware.Cors(),
		middleware.Logger(),
		middleware.RecoverWithLog(logger.Log()),
	)
}
